package com.ruoyi.feike.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.ruoyi.activiti.service.impl.ActTaskServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.InstanceIdUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.mapper.NotesMapper;
import com.ruoyi.feike.service.*;
import lombok.extern.slf4j.Slf4j;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lss
 * @version 1.0
 * @description: TODO
 * @date 2022/8/2 16:13
 */
@Service
@Slf4j
public class NewApplicationServiceImpl implements INewApplicationService {

    private static final String INSTEANCEID="depositDecrease";

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private IBasicInformationService basicInformationService;

    @Autowired
    private IDealerNegativeInformationCheckService dealerNegativeInformationCheckService;

    @Autowired
    private ILimitCalculationForCommericalNeedsService limitCalculationForCommericalNeedsService;

    @Autowired
    private IOtherFinancingResourceService otherFinancingResourceService;

    @Autowired
    private ITemporaryConditionFollowUpService temporaryConditionFollowUpService;

    @Autowired
    private ISecuritiesService securitiesService;

    @Autowired
    private InstanceIdUtil instanceIdUtil;

    @Autowired
    private NotesMapper notesMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ActTaskServiceImpl actTaskService;

    /**
     * @param newApplicationDTO
     * @description: 新经销商申请审批流程接口
     * @param: newApplicationDTO
     * @return: AjaxResult
     * @author lss
     * @date: 2022/8/2 15:15
     */
    @Override
    @Transactional
    public AjaxResult insertNewApplication(NewApplicationDTO newApplicationDTO) {
        //生成流程task
        String currentVal = instanceIdUtil.getRedisInstanceId("DD");
        String instanceId = instanceIdUtil.getIstanceId("DD", currentVal);

        Notes notes = new Notes();
        notes.setComments(newApplicationDTO.getComments());
        notes.setId(IdUtils.simpleUUID());
        notes.setInstanceId(instanceId);
        notesMapper.insertNotes(notes);
        //String instanceId = IdUtils.get16UUID();
        Deployment deployment = repositoryService.createDeployment().key(INSTEANCEID).deploy();
        String title = deployment.getName();
        Authentication.setAuthenticatedUserId(String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder.start().withProcessDefinitionKey(INSTEANCEID).withName(title).withBusinessKey(instanceId).build());
        //查询任务信息
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();




        TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
        List<Task> todoList = query.list();//获取申请人的待办任务列表
        for (Task tmp : todoList) {
            if(tmp.getProcessInstanceId().equals(processInstance.getId())){
                task = tmp;//获取当前流程实例，当前申请人的待办任务
                break;
            }
        }
        Map<String,Object> map=new HashMap<>();
        HashMap<String, Object> variables = new HashMap<String, Object>();
        List<Map<String, Object>> actForm = (List<Map<String, Object>>) map.get("actForm");
        for (Map<String, Object> form : actForm) {
            variables.put(String.valueOf(form.get("controlId")), form.get("controlValue"));
        }
        variables.put("toUnderwriter", 0);
        taskService.complete(task.getId(), variables);

        //发送邮件
        try {
            org.activiti.engine.runtime.ProcessInstance processInstanceMe = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
            org.activiti.engine.task.Task finalTask = taskService.createTaskQuery()
                    .processInstanceId(processInstanceMe.getProcessInstanceId())
                    .singleResult();
            ThreadUtil.execute(new Runnable() {

                @Override
                public void run() {
                    actTaskService.sendMail(finalTask, instanceId,null);
                }
            });
        } catch (Exception e) {
            log.error("邮件发送失败，{}",e.getMessage());
        }

        //插入基本信息
        int basicInfoFlag=0;
//        if (newApplicationDTO.getDealername()!=null){
//            basicInfoFlag=basicInformationService.insertBasicInformation(newApplicationDTO.getDealername());
//        }
        //经销商信息
        int dealerInfoFlag=0;
        if (basicInfoFlag==1&& StringUtils.isNotEmpty(newApplicationDTO.getDealerInformationList())){
            for (DealerNegativeInformationCheck dealerNegativeInformationCheck:newApplicationDTO.getDealerInformationList()){
                            dealerInfoFlag=dealerNegativeInformationCheckService.insertDealerNegativeInformationCheck(dealerNegativeInformationCheck);
            }
        }
        //销售业绩及目标
        int salstargetFlag=0;
        if (dealerInfoFlag==1&&StringUtils.isNotEmpty(newApplicationDTO.getLimit_calculation_for_commerical_needs())){
            for (LimitCalculationForCommericalNeeds limitCalculationForCommericalNeedsm:newApplicationDTO.getLimit_calculation_for_commerical_needs()){
                salstargetFlag=limitCalculationForCommericalNeedsService.insertLimitCalculationForCommericalNeeds(limitCalculationForCommericalNeedsm);
            }
        }
        //经销商其他相关贷款信息
        int otherFinancFlag=0;
        if (salstargetFlag==1&&StringUtils.isNotEmpty(newApplicationDTO.getOther_financing_resource())){
            for (OtherFinancingResource otherFinancingResource:newApplicationDTO.getOther_financing_resource()){
                otherFinancFlag=otherFinancingResourceService.insertOtherFinancingResource(otherFinancingResource);
            }
        }
        //经销商创建相关信息
        int temporaryFlag=0;
        if (otherFinancFlag==1&&StringUtils.isNotEmpty(newApplicationDTO.getTemporaryConditionFollowUpList())){
            for (TemporaryConditionFollowUp temporaryConditionFollowUp:newApplicationDTO.getTemporaryConditionFollowUpList()){
                temporaryFlag=temporaryConditionFollowUpService.insertTemporaryConditionFollowUp(temporaryConditionFollowUp);
            }
        }
        //担保信息
        int securityFlag=0;
        if (temporaryFlag==1&&StringUtils.isNotEmpty(newApplicationDTO.getTemporaryConditionFollowUpList())){
            for ( Securities securities:newApplicationDTO.getSecuritieList()){
                securityFlag=securitiesService.insertSecurities(securities);
            }
        }
        return AjaxResult.success("添加新经销商申请成功!");
    }
}
